import logging
import os.path

from django.conf import settings
from django.contrib.auth import authenticate, login
from django.shortcuts import render

from chat.response import Success, Failure
from .models import Message
from django.views.decorators.http import require_http_methods

# 日志信息记录到文件
logging.basicConfig(filename='chat.log', level=logging.DEBUG)


# 登录接口
def my_login(request):
    username = request.POST["username"]
    password = request.POST["password"]
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)

        # Redirect to a success page.
        return Success("登录成功！")
    else:
        # Return an 'invalid login' error message.
        return Failure('登录失败!')
    # http -f POST http://localhost:8000/chat/login/ username='hongzhe' password=1234


# 主页
def index(request):
    return render(request, "chat/login.html")


# 聊天室
def room(request, room):
    # 获取用户名
    username = request.GET.get('username')
    # 查询历史消息
    msgs = Message.objects.filter(room=room).order_by('create_time')
    # 记录调试信息
    logging.debug(f'msgs: {msgs}')
    logging.debug(f'房间名: {msgs} ')
    # 当前房间名
    current_room_name = room

    # 设置session
    request.session['username'] = username
    request.session.set_expiry(15 * 60)  # 15分钟过期

    # 房间名称列表
    rooms = Message.objects.values_list('room', flat=True).distinct()
    room_names = list(rooms)

    if settings.DEBUG:
        return render(request, "chat/wxroom_test.html", locals())
    else:
        print("生产环境")
        return render(request, "chat/wxroom.html", locals())


# 历史聊天记录
@require_http_methods(['GET'])
def get_messages(request):
    # 获取房间名
    room = request.GET.get('room')

    messages = Message.objects.filter(room=room).order_by('create_time')

    message_list = []
    for message in messages:
        # 如果是图片消息，那么将文本内容置空
        if message.image:
            message.content = None

        message_dict = {
            'username': message.username,
            'room': message.room,
            'content': message.content,
            'create_time': message.create_time.strftime("%Y年%m月%d日 %H:%M:%S"),
            'image': message.image.url if message.image else None
        }
        message_list.append(message_dict)

    return Success("获取成功！", message_list)


# 冗余文件删除详情页
def delete_detail(request, room):
    difference = []
    messages = Message.objects.filter(room=room)
    path = os.path.join(os.getcwd(), 'static', 'media')

    images_path = [i.image.url.replace('/', '') for i in messages if i.image]

    for root, dirs, files in os.walk(path, topdown=False):
        for name in files:
            if name not in images_path:
                difference.append(name)
    if settings.DEBUG:
        return render(request, "chat/delete_detail_test.html", {"data": difference})
    return render(request, "chat/delete_detail.html", {"data": difference})


# 删除文件
def delete_file(request):
    path = os.path.join(os.getcwd(), 'static', 'media', request.GET.get('path'))
    print(f"删除文件为：{path}")
    if os.path.exists(path):
        os.remove(path)
        return Success("成功!")
    return Failure("删除失败！")


# 房间名列表
@require_http_methods(['GET'])
def get_room_name(request):
    rooms = Message.objects.values_list('room', flat=True).distinct()[:5]
    room_names = list(rooms)
    return Success("成功!", room_names)


# 搜索房间
@require_http_methods(['GET'])
def search_room(request):
    # 获取房间名
    room_query = request.GET.get('room')

    if room_query:
        room_name = Message.objects.filter(room__icontains=room_query).values_list('room', flat=True).first()

        if room_name:
            return Success("成功!", [room_name])

    return Failure("失败!", [])


# 添加房间
@require_http_methods(['GET'])
def add_room(request):
    # 获取房间名
    room_query = request.GET.get('room')
    Message.objects.create(username='管理员', room=room_query, content='房间创建成功！')

    return Success("成功!", [])


# 删除房间
@require_http_methods(['GET'])
def delete_room(request):
    # 获取房间名
    room_query = request.GET.get('room')

    # 删除房间为 room_query 的所有消息
    messages_deleted = Message.objects.filter(room=room_query).delete()

    # 检查是否删除成功
    if messages_deleted[0] > 0:
        return Success(f"房间：{room_query}删除成功!", [])

    return Failure("未找到房间或房间没有消息。", [])


from django.http import JsonResponse


# 撤回消息
@require_http_methods(['GET'])
def undo_message(request):
    # 获取房间名
    room_query = request.GET.get('room')
    username = request.GET.get('username')

    # 删除房间room_query，并且用户为username的最后一条消息
    messages = Message.objects.filter(room=room_query, username=username).order_by('-create_time')
    print(messages[0])
    if not messages:
        return Failure("删除失败!", [])

    message_dict = {
        'username': messages[0].username,
        'room': messages[0].room,
        'content': messages[0].content,
        'create_time': messages[0].create_time.strftime("%Y年%m月%d日 %H:%M:%S"),
        'image': messages[0].image.url if messages[0].image else None
    }

    messages[0].delete()

    return Success("删除成功!", [message_dict])
